{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "90c47ece-a885-442c-a8cd-baeedb04c7a1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import io\n",
    "import panel as pn\n",
    "import pandas as pd\n",
    "import hvplot.pandas\n",
    "\n",
    "pn.extension(template='fast')\n",
    "\n",
    "pn.state.template.title = 'hvPlot Explorer'"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f3d89bef-89d2-42fd-ab00-5f0d8f800a27",
   "metadata": {},
   "source": [
    "This example demonstrates how to leverage the hvPlot explorer functionality when combined with a FileInput widget to allow users to explore their own data. When a user uploads their own data it gets added to the list of datasets the user can select from."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "732b5d4a-6181-4194-8c5f-6f989dabbb3a",
   "metadata": {},
   "outputs": [],
   "source": [
    "upload = pn.widgets.FileInput(name='Upload file', height=50)\n",
    "select = pn.widgets.Select(options={\n",
    "    'Penguins': 'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv',\n",
    "    'Diamonds': 'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/diamonds.csv',\n",
    "    'Titanic': 'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/titanic.csv',\n",
    "    'MPG': 'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/mpg.csv'\n",
    "})\n",
    "\n",
    "def add_data(event):\n",
    "    b = io.BytesIO()\n",
    "    upload.save(b)\n",
    "    b.seek(0)\n",
    "    name = '.'.join(upload.filename.split('.')[:-1])\n",
    "    select.options[name] = b\n",
    "    select.param.trigger('options')\n",
    "    select.value = b\n",
    "    \n",
    "upload.param.watch(add_data, 'filename')\n",
    "\n",
    "def explore(csv):\n",
    "    df = pd.read_csv(csv)\n",
    "    explorer = hvplot.explorer(df)\n",
    "    def plot_code(**kwargs):\n",
    "        code = f'```python\\n{explorer.plot_code()}\\n```'\n",
    "        return pn.pane.Markdown(code, sizing_mode='stretch_width')\n",
    "    return pn.Column(\n",
    "        explorer,\n",
    "        '**Code**:',\n",
    "        pn.bind(plot_code, **explorer.param.objects())\n",
    "    )\n",
    "\n",
    "widgets = pn.Column(\n",
    "    \"Select an existing dataset or upload one of your own CSV files and start exploring your data.\",\n",
    "    pn.Row(\n",
    "        select,\n",
    "        upload,\n",
    "    )\n",
    ").servable()  \n",
    "\n",
    "output = pn.panel(pn.bind(explore, select)).servable()\n",
    "\n",
    "pn.Column(widgets, output)"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
